package com.wwwarehouse.common.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.ConvertToPcParams;
import com.wwwarehouse.common.bean.PushImportSucessBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.bean.response.ConvertToPcBean;
import com.wwwarehouse.common.common.Common;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.eventbus_event.CardDeskEvent;
import com.wwwarehouse.common.eventbus_event.PushImportEvent;
import com.wwwarehouse.common.eventbus_event.StartImportEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ApkTools;
import com.wwwarehouse.common.tools.rsa.StringUtils;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

/**
 * Created by feng.gao on 2017/10/20.
 * 手机转PC统一跳转页面
 */
@Route(path = Constant.CONVERT_TOPC_EMPTY_FRAGMENT)

public class ConvertToPcEmptyFragment extends BaseFragment implements View.OnClickListener {
    private StateLayout mStateLayout;
    private ConvertToPcParams mConvertToPcParams;
    private String title;
    private RelativeLayout mContentRl; //内容布局
    private LinearLayout mUrlLayout; //生成短链接页面
    private LinearLayout mDurationTimeLayout; //计时页面
    private ConvertToPcBean bean; //页面展示需要的实体


    //	短连接页面的
    private TextView mWebAddressTv;
    private ImageView mWechatIv;

    //  计时页面的
    private TextView mTimeTv;
    private TextView mUrlTv;
    private Timer timer;
    private TimerTask timerTask;
    private long cnt;
    private long mTimeCost;
    private String mUrl;

    //	标识跳转不同导入页
    private String mAroutePath;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.convert_to_pc_empty_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);


    }

    private void initView(View view) {
        EventBus.getDefault().register(this);
        mStateLayout = (StateLayout) view.findViewById(R.id.gaofeng_sl_state);
        mContentRl = (RelativeLayout) view.findViewById(R.id.content_rl);
        mUrlLayout = (LinearLayout) view.findViewById(R.id.url_layout);
        mDurationTimeLayout = (LinearLayout) view.findViewById(R.id.duration_time_layout);
        //全部隐藏只留状态页
        mContentRl.setVisibility(View.INVISIBLE);
        mUrlLayout.setVisibility(View.INVISIBLE);
        mDurationTimeLayout.setVisibility(View.INVISIBLE);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ConvertToPcEmptyFragment && StringUtils.isNoneNullString(title)) {
            mActivity.setTitle(title);
        }
    }

    @Override
    public void requestDatas() {
        if (getArguments() != null && getArguments().getSerializable(Constant.KEY_CONVERT_TO_PC) != null) {
            mConvertToPcParams = (ConvertToPcParams) getArguments().getSerializable(Constant.KEY_CONVERT_TO_PC);
            if (mConvertToPcParams != null && mConvertToPcParams.getMap() != null && mConvertToPcParams.getUrl() != null && mConvertToPcParams.getImportSuccessArouterPath() != null) {
                title = mConvertToPcParams.getTitle();
                if (StringUtils.isNoneNullString(title)) {
                    mActivity.setTitle(title);
                }
                mAroutePath = mConvertToPcParams.getImportSuccessArouterPath();
                mStateLayout.showProgressView(true);
                NoHttpUtils.httpPost(mConvertToPcParams.getUrl(), mConvertToPcParams.getMap(), new NoHttpUtils.OnResponseListener() {
                    @Override
                    public void onSucceed(CommonClass commonClass, int what) {
                        if (commonClass != null && commonClass.getData() != null && commonClass.getCode() != null) {
                            if (commonClass.getCode().equals("0")) {
                                mContentRl.setVisibility(View.VISIBLE);
                                bean = JSON.parseObject(commonClass.getData().toString(), ConvertToPcBean.class);
                                if (bean != null) {
                                    mStateLayout.showContentView();
                                    if (StringUtils.isNoneNullString(bean.getUrl())) {
                                        mUrl = bean.getUrl();
                                    }
                                    if (StringUtils.isNoneNullString(bean.getPageType()) && bean.getPageType().equals("1")) {
                                        //跳转到生成短链接的页面
                                        mUrlLayout.setVisibility(View.VISIBLE);
                                        mDurationTimeLayout.setVisibility(View.INVISIBLE);
                                        setUrlLayoutData();
                                    } else if (StringUtils.isNoneNullString(bean.getPageType()) && bean.getPageType().equals("2")) {
                                        //跳转到时间页面
                                        mUrlLayout.setVisibility(View.INVISIBLE);
                                        mDurationTimeLayout.setVisibility(View.VISIBLE);
                                        if (bean != null && StringUtils.isNoneNullString(bean.getTimeCost())) {
                                            mTimeCost = Long.valueOf(bean.getTimeCost());
                                            setDurationTimeData(mTimeCost , bean.getUrl());

                                        }
                                    }
                                }
                            } else {
                                mStateLayout.showSystemView(commonClass.getMsg(), true);
                                mStateLayout.setSystemListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        requestDatas();
                                    }
                                });
                            }

                        } else {
                            mStateLayout.showEmptyView(true);
                            mStateLayout.setSystemListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    requestDatas();
                                }
                            });
                        }

                    }

                    @Override
                    public void onFailed(String result, int what) {
                        mStateLayout.showSystemView(result, true);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestDatas();
                            }
                        });
                    }

                    @Override
                    public void onFinish(int what) {

                    }
                }, 1);
            } else {
                mStateLayout.showSystemView(true);
                mStateLayout.setSystemListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        requestDatas();
                    }
                });
            }
        } else {
            mStateLayout.showSystemView(true);
            mStateLayout.setSystemListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestDatas();
                }
            });
        }
    }

    private void setDurationTimeData(long mTimeCost , String url) {
        mTimeTv = (TextView) mDurationTimeLayout.findViewById(R.id.time_task_view);
        mUrlTv = (TextView) mDurationTimeLayout.findViewById(R.id.url_tv);
        if (StringUtils.isNoneNullString(url)) {
//            mUrlTv.setText(url);
        }
        mDurationTimeLayout.findViewById(R.id.btn_confirm).setOnClickListener(this);
        timer = new Timer();
        cnt = mTimeCost;
        startClick();
    }

    private void setUrlLayoutData() {
        mWebAddressTv = (TextView) mUrlLayout.findViewById(R.id.web_address_tv);
        mWechatIv = (ImageView) mUrlLayout.findViewById(R.id.share_wechat_iv);
        mUrlLayout.findViewById(R.id.share_qq_iv).setOnClickListener(this);
        mWechatIv.setOnClickListener(this);
        if (!ApkTools.isWeixinInstall(mActivity)) {
            mWechatIv.setVisibility(View.GONE);
        }
        if (bean != null && bean.getUrl() != null) {
            mUrl = bean.getUrl();
            mWebAddressTv.setText("操作网址：" + bean.getUrl());
        }

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.share_qq_iv) {
            if (mUrl != null) {
                Common.getInstance().shareQQ(mActivity, mUrl, "", "", mUrl);
            }
        } else if (v.getId() == R.id.share_wechat_iv) {
            if (mUrl != null) {
                Common.getInstance().shareWeixinTextMoment(mActivity, mUrl);
            }
        } else if (v.getId() == R.id.btn_confirm) {
            EventBus.getDefault().post(new CardDeskEvent("clear_back_stack"));
        }
    }


    /**
     * 接收推送消息，跳转到导入成功页面。
     *
     * @param pushImportEvent
     */
    public void onEventMainThread(PushImportEvent pushImportEvent) {
        if (peekFragment() instanceof ConvertToPcEmptyFragment) {
//				开始判断跳转不同的导入成功页面
            if (StringUtils.isNoneNullString(mAroutePath)) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.KEY_CONVER_TO_PC_IMPORT_SUCCESS, pushImportEvent.getResult());
                popFragment();
                pushFragment(mAroutePath, bundle);
            }
        }
    }

    /**
     * 接收推送消息，跳转到计时页面。
     *
     * @param startImportEvent
     */
    public void onEventMainThread(StartImportEvent startImportEvent) {
        if (peekFragment() instanceof ConvertToPcEmptyFragment) {
            PushImportSucessBean mStartImportBean = JSON.parseObject(startImportEvent.getResult(), PushImportSucessBean.class);
            if (bean != null && StringUtils.isNoneNullString(bean.getOperationUkid())
                    && StringUtils.isNoneNullString(mStartImportBean.getMsg().getOperationUkid())) {
                if (mStartImportBean != null && mStartImportBean.getMsg() != null) {
                    if (bean.getOperationUkid().equals(mStartImportBean.getMsg().getOperationUkid())) {
                        if (!TextUtils.isEmpty(mStartImportBean.getMsg().getTimeCost())) {
                            if (mDurationTimeLayout.getVisibility() == View.INVISIBLE) {
                                mUrlLayout.setVisibility(View.INVISIBLE);
                                mDurationTimeLayout.setVisibility(View.VISIBLE);
                                mTimeCost = Long.valueOf(mStartImportBean.getMsg().getTimeCost());
                                setDurationTimeData(mTimeCost , mUrl);
                            }
                        }
                    }
                }
            }

        }
    }


    /**
     * 格式化时间
     *
     * @param cnt
     * @return
     */
    private String getStringTime(long cnt) {
        long hour = cnt / 3600;
        long min = cnt % 3600 / 60;
        long second = cnt % 60;
        return String.format(Locale.CHINA, "%02d:%02d:%02d", hour, min, second);
    }


    /**
     * 开始计时
     */
    public void startClick() {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTimeTv.setText(getStringTime(cnt++));

                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
